$(function () {
    initTree();

    $("#BtnAdd").bind('click', addRole);

    $("#BtnUpdate").bind('click', updateRole);

    $('#BtnDel').bind('click', deletRole);

    $('#BtnGrant').bind('click', grant);

    $('#BtnAddUserToRole').bind('click', addUserToRole);

    $('#BtnDelUserFromRole').bind('click', delUserFromRole);
});

var ztreeRole;
var role_id="";

function initTree() {
    var setting = {
        async: {
            enable: true,
            url: base + "/private/sys/role/tree",
            autoParam: ["id"]
        }
        , view: {
            nameIsHTML: true
        }
        , data: {
            simpleData: {
                enable: true
            }
        }
    };
    ztreeRole = $.fn.zTree.init($("#treeDemo"), setting);
}

var addRole = function () {
    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form()
            , laytpl = layui.laytpl
            , layer = layui.layer;
        projectSelectInit();
        layerAddOpen("roleAddForm", "新增角色信息", contentAddDiv(role_id));
    });
}

var projectSelectInit = function () {
    $.ajax({
        url: base + "/private/sys/role/projList",
        success: function (data) {
            data = JSON.parse(data);
            if (data != null) {
                var optionstring = "";
                $.each(data, function (i, item) {
                    optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
                });
                $("select[name='unitid']").html('<option value="">无</option>' + optionstring);
            } else {
                $("select[name='unitid']").html('<option value="">无</option>');
            }
            form.render();
        }
    });
}


var layerAddOpen = function (id, title, content) {
    layer.open({
        id: id
        , type: 1
        , title: title
        , content: content
        , area: ['500px', '400px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();

            //提交角色验证
            var obj = $("input[name='name']");
            if (data.name == "") {
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }

            if (data.name != "") {
                $.ajax({
                    type: "post",
                    url: base + "/private/sys/role/isexistsname?name=" + data.name,
                    async: false,
                    success: function (isTrue) {
                        if (isTrue == "true") {
                            obj.focus();
                            layer.tips('角色已经存在!', obj);
                            return false;
                        } else {
                            $.ajax({
                                url: base + "/private/sys/role/add",
                                type: "POST",
                                data: data,
                                success: function (res) {
                                    layer.msg("角色信息已添加成功！", {
                                        time: 1000, //1s后自动关闭
                                    });
                                    layer.close(index);
                                    //添加完成后刷新树
                                    reloadTree(data, res);
                                    list(res);
                                },
                                fail: function (res) {
                                    layer.msg('系统错误！', {
                                        icon: 5
                                    });
                                }
                            });
                        }
                    }
                });
            }
        }, success: function () {
            //  bindDataToUpdateForm(data);
        }
    });
}

var contentAddDiv = function (role_id) {
    var content;
    var data = {
        "title": {
            "id": "",
            "name": "角色名称:",
            "unitid": "所属项目:",
            "descript": "角色描述:"
        }, "text": {
            "id": role_id,
            "name": "",
            "unitid": "",
            "descript": "描述"
        }, "input": {
            "id": "hidden",
            "name": "text",
            "unitid": "select",
            "descript": "textarea"
        }, "input_init": {}
    };
    var getDiv = "";
    if (dc_update.length > 1) {
        getDiv = dc_update[0].innerHTML;
    } else {
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
}

//添加完成后展开到该节点
var reloadTree = function (data, res) {
    if (data != null) {
        if (res != null && res != "") {
            var nodelist = ztreeRole.getNodes()[0];
            var nodeNew = {
                "name": data.name,
                "checked": false,
                "pId": "",
                "id": res,
                "url": "javascript:list(" + res + ")",
                "target": "_self"
            }
            var node= ztreeRole.addNodes(nodelist,-1,nodeNew);
            var lastnode = nodelist.children[nodelist.children.length-1];
            ztreeRole.selectNode(lastnode);//指定选中ID的节点
            ztreeRole.reAsyncChildNodes(lastnode, "refresh", false);
        }
        return;
    }
}

var updateRole = function (){
    if (role_id == null || role_id == "" || role_id == undefined) {
        layer.msg("请选中需要更新的角色！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }

    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form()
            , laytpl = layui.laytpl
            , layer = layui.layer;
        projectSelectInit();
        layerEditOpen("roleEditForm", "编辑角色信息", contentEditDiv(role_id));
    });
}

var layerEditOpen=function (id,title,content) {
    layer.open({
        id: id
        , type: 1
        , title: title
        , content: content
        , area: ['500px', '400px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();

            //提交角色验证
            var obj = $("input[name='name']");
            if (data.name == "") {
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }

            if (data.name != "") {
                $.ajax({
                    url: base + "/private/sys/role/update",
                    type: "POST",
                    data: data,
                    success: function (res) {
                        layer.close(index);
                        //添加完成后刷新树
                        updateTreeNode(data.id);
                    },
                    fail: function (res) {
                        layer.msg('系统错误！', {
                            icon: 5
                        });
                    }
                });
            }
        }, success: function () {
            $.ajax({
                url: base + "/private/sys/role/getrole",
                type: "POST",
                data: {roleid:role_id},
                async:false,
                success: function (res) {
                    bindDataToUpdateForm(JSON.parse(res));
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        }
    });
}

var bindDataToUpdateForm=function (data) {
    // alert(JSON.stringify(data));
    $("input[name='name']").val(data.name);
    $("textarea[name='descript']").val(data.descript);
    //alert(data.descript);
    //form.render();
}

//更新成功后刷新树节点
var updateTreeNode=function (nodeId) {
    var node = ztreeRole.getNodeByParam("id", nodeId);
    ztreeRole.selectNode(node);
    ztreeRole.reAsyncChildNodes(node, "refresh", false);
    list(nodeId);
}

var contentEditDiv =function (role_id) {
    var content;
    var data = {
        "title": {
            "id": "",
            "name": "角色名称:",
            "unitid": "所属项目:",
            "descript": "角色描述:"
        }, "text": {
            "id": role_id,
            "name": "",
            "unitid": "",
            "descript": ""
        }, "input": {
            "id": "hidden",
            "name": "text",
            "unitid": "select",
            "descript": "textarea"
        }, "input_init": {}
    };
    var getDiv = "";
    if (dc_update.length > 1) {
        getDiv = dc_update[0].innerHTML;
    } else {
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
}

var deletRole = function () {
    if (role_id == null || role_id == "" || role_id == undefined) {
        layer.msg("请选中需要删除的角色！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }

    layer.confirm('删除角色,该角色对应的资源和所属的用户会被一起删除，您确认要删除吗？', {
        btn: ['删除', '取消'] //按钮
    }, function (index, layero) {
        $.ajax({
            url: base + "/private/sys/role/delete",
            data: {id: role_id},
            type: "POST",
            async: false,
            success: function (res) {
                layer.msg('已成功删除！', {
                    time: 1000, //20s后自动关闭
                });
                removeTreeNode(role_id);
            },
            fail: function (res) {
                layer.msg('系统错误！', {
                    icon: 5
                });
            }
        });
    });
}

//删除完成后展开当前删除节点的父节点并选中.
var removeTreeNode = function (nodeId) {
    var node = ztreeRole.getNodeByParam("id", nodeId);
    ztreeRole.removeNode(node);
    var nodelist = ztreeRole.getNodes()[0].children;
    var lastnode = nodelist[nodelist.length-1];
    ztreeRole.selectNode(lastnode);
    ztreeRole.reAsyncChildNodes(lastnode, "refresh", false);
    list(lastnode.id);
}

var grant = function () {
    if (role_id == null || role_id == "" || role_id == undefined) {
        layer.msg("请选择角色！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
    layer.open({
        title:"权限分配",
        type: 2,
        anim:-1,
        area: ['800px', '600px'], //宽高
        resize:false, //禁止拉伸
        scrollbar: true,//允许出现滚动条
        content: [base+"/private/sys/role/toMenuGrant?roleid="+role_id,'no'],
        btn: ['确认', '取消'],
        yes:function(index,layero){
            var iframeWin = window[layero.find('iframe')[0]['name']];
            var ids = iframeWin.getIdsTree()
            $.ajax({
                url: base + "/private/sys/role/menu",
                data: {roleid: role_id,checkids:ids},
                type: "POST",
                async: false,
                success: function (res) {
                    //更新表单
                    layer.msg('权限已成功分配！', {
                        time: 1000, //20s后自动关闭
                    });
                    layer.close(index);
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        }
    });
}

//添加用户到角色
var addUserToRole = function () {
    if (role_id == null || role_id == "" || role_id == undefined) {
        layer.msg("请选择角色！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
    layer.open({
        title:"用户信息",
        type: 2,
        anim:-1,
        area: ['1000px', '600px'], //宽高
        resize:false, //禁止拉伸
        content: [base+"/private/sys/role/getuser",'no'],
        btn: ['确认', '取消'],
        yes:function(index,layero){
            var iframeWin = window[layero.find('iframe')[0]['name']];
           // console.log(iframeWin.getCheckedJson("userlist"));
            var ids = selectUser(iframeWin);
            $.ajax({
                url: base + "/private/sys/role/addroleuser",
                data: {roleid: role_id,checkids:ids},
                type: "POST",
                async: false,
                success: function (res) {
                    layer.msg('已成功添加用户到角色！', {
                        time: 1000, //20s后自动关闭
                    });
                    //更新表单
                    layer.close(index);
                    list(role_id);
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        }
    });
}

var selectUser=function (iframe) {
    var ids = iframe.getCheckedJson("userlist");
    var selects_ids =[];
    if(ids.length<=0){
        layer.msg("请选择用户！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }else{
        $.each(ids,function (index, item) {
            selects_ids.push(item.id);
        })
    }
    return selects_ids.toString();
}


//删除角色所拥有的用户
var delUserFromRole = function () {
    if (role_id == null || role_id == "" || role_id == undefined) {
        layer.msg("请选择角色！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
    var ids = selectUser(window);
    $.ajax({
        type: 'post',
        url: base + "/private/sys/role/delroleuser",
        data: {"roleid": role_id,checkids:ids},
        success: function (data) {
            layer.msg('已成功将用户从角色中移除！', {
                time: 1000, //20s后自动关闭
            });
            list(role_id);
        },
        fail: function (res) {
            layer.msg('系统错误！', {
                icon: 5
            });
        }
    });
}

var list = function (roleid) {
    $.ajax({
        type: 'post',
        url: base + "/private/sys/role/getrole",
        data: {"roleid": roleid},
        success: function (data) {
                data = JSON.parse(data);
                $('#name').html(data.name);
                $('#descript').html(data.descript);
                loadUserTable(roleid, 1);
                //传递全局的role_id供删除使用
                role_id = roleid;
                role_name = data.name;
        },
        fail: function (res) {
            layer.msg('系统错误！', {
                icon: 5
            });
        }
    });
}

var loadUserTable = function (roleId, num) {
    var param = {
        roleid: roleId,
        page_num: num,
        page_size: "10"
    };
    $.ajax({
        url: base + "/private/sys/role/list",
        data: param,
        success: function (data, textStatus, jqXHR) {
            data = JSON.parse(data);
            var pageCount = data.pageCount;
            var dataObj = {
                "list": data.rows,
                "dataTool": {
                    "title": {
                        "loginname": "用户名"
                        , "realname": "姓名"
                        , "state": "帐户状态"
                        , "position": "职务"
                        , "email": "电子邮件"
                        , "telephone": "固定电话"
                        , "mobile": "手机号码"
                    },
                    "titleCheckbox": true,
                    "noDataStatus": true
                }
            };

            showPageTable('userlist', dataObj, num, pageCount, "initTableData");
        },
        error: function () {
        }
    });
}